package logic

import (
	"context"
	"srv/internal/svc"
	"srv/model/mysql"
	"srv/pkg"
	"srv/retaiers"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *retaiers.AddOrderRequest) (*retaiers.AddOrderResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.Int(int(in.GoodsId))
	if err != nil {
		return nil, err
	}
	if g.ID == 0 {
		return nil, err
	}
	if g.GoodsStock < int(in.Num) {
		return nil, err
	}
	or := mysql.Orders{
		UserId:     in.UserId,
		OrderSn:    in.OrderSn,
		Amount:     float64(in.Amount),
		Payment:    int(in.Payment),
		Status:     g.GoodsStatus,
		GodsId:     uint(in.GoodsId),
		GoodsTitle: g.GoodsTitle,
		GoodsNum:   int(in.Num),
		GoodsPrice: g.GoodsPrice,
	}
	err = or.Create()
	if err != nil {
		return nil, err
	}
	pay := pkg.NewALiPay()
	amount := strconv.FormatFloat(float64(in.Amount), 'f', 1, 64)
	aliPay := pay.ALIPay(g.GoodsTitle, in.OrderSn, amount)
	return &retaiers.AddOrderResponse{Ali: int64(or.ID), Url: aliPay}, nil
}
